import 'package:flutter/material.dart';
import '../models/folder_model.dart';
import '../theme/app_theme.dart';
import '../utils/responsive_layout.dart';
import 'modern_card.dart';

/**
 * 可拖拽的文件夹项组件
 * 支持拖拽排序、层级显示和各种交互操作
 */
class DraggableFolderItem extends StatefulWidget {
  final FolderModel folder;
  final int level;
  final bool isSelected;
  final bool isDragTarget;
  final VoidCallback? onTap;
  final VoidCallback? onLongPress;
  final VoidCallback? onExpansionToggle;
  final Function(String folderId)? onDelete;
  final Function(String folderId, String newName)? onRename;
  final Function(String folderId, Color? color)? onColorChange;
  final Function(String folderId, IconData? icon)? onIconChange;
  final Function(String folderId)? onPin;
  final Function(FolderDragData dragData)? onDragStarted;
  final Function(FolderDragData dragData, String? targetFolderId, int? targetIndex)? onDragCompleted;
  final bool enableDrag;
  final bool showActions;
  final Widget? trailing;

  const DraggableFolderItem({
    Key? key,
    required this.folder,
    this.level = 0,
    this.isSelected = false,
    this.isDragTarget = false,
    this.onTap,
    this.onLongPress,
    this.onExpansionToggle,
    this.onDelete,
    this.onRename,
    this.onColorChange,
    this.onIconChange,
    this.onPin,
    this.onDragStarted,
    this.onDragCompleted,
    this.enableDrag = true,
    this.showActions = true,
    this.trailing,
  }) : super(key: key);

  @override
  State<DraggableFolderItem> createState() => _DraggableFolderItemState();
}

class _DraggableFolderItemState extends State<DraggableFolderItem>
    with SingleTickerProviderStateMixin {
  bool _isHovered = false;
  bool _isDragging = false;
  bool _isRenaming = false;
  late TextEditingController _renameController;
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;

  @override
  void initState() {
    super.initState();
    _renameController = TextEditingController(text: widget.folder.name);
    _animationController = AnimationController(
      duration: const Duration(milliseconds: 200),
      vsync: this,
    );
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 1.05,
    ).animate(CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
    ));
  }

  @override
  void dispose() {
    _renameController.dispose();
    _animationController.dispose();
    super.dispose();
  }

  void _startRename() {
    setState(() {
      _isRenaming = true;
    });
    _renameController.text = widget.folder.name;
    _renameController.selection = TextSelection(
      baseOffset: 0,
      extentOffset: widget.folder.name.length,
    );
  }

  void _finishRename() {
    if (_renameController.text.trim().isNotEmpty &&
        _renameController.text.trim() != widget.folder.name) {
      widget.onRename?.call(widget.folder.id, _renameController.text.trim());
    }
    setState(() {
      _isRenaming = false;
    });
  }

  void _cancelRename() {
    setState(() {
      _isRenaming = false;
    });
    _renameController.text = widget.folder.name;
  }

  void _showContextMenu(BuildContext context, Offset position) {
    showMenu(
      context: context,
      position: RelativeRect.fromLTRB(
        position.dx,
        position.dy,
        position.dx + 1,
        position.dy + 1,
      ),
      items: <PopupMenuEntry<String>>[
        PopupMenuItem(
          value: 'rename',
          child: const Row(
            children: [
              Icon(Icons.edit, size: 18),
              SizedBox(width: 8),
              Text('重命名'),
            ],
          ),
        ),
        PopupMenuItem(
          value: 'color',
          child: const Row(
            children: [
              Icon(Icons.color_lens, size: 18),
              SizedBox(width: 8),
              Text('更改颜色'),
            ],
          ),
        ),
        PopupMenuItem(
          value: 'icon',
          child: const Row(
            children: [
              Icon(Icons.emoji_emotions, size: 18),
              SizedBox(width: 8),
              Text('更改图标'),
            ],
          ),
        ),
        PopupMenuItem(
          value: 'pin',
          child: Row(
            children: [
              Icon(widget.folder.isPinned ? Icons.push_pin : Icons.push_pin_outlined, size: 18),
              const SizedBox(width: 8),
              Text(widget.folder.isPinned ? '取消置顶' : '置顶'),
            ],
          ),
        ),
        const PopupMenuDivider(),
        PopupMenuItem(
          value: 'delete',
          child: const Row(
            children: [
              Icon(Icons.delete, size: 18, color: Colors.red),
              SizedBox(width: 8),
              Text('删除', style: TextStyle(color: Colors.red)),
            ],
          ),
        ),
      ],
    ).then((value) {
      switch (value) {
        case 'rename':
          _startRename();
          break;
        case 'color':
          _showColorPicker();
          break;
        case 'icon':
          _showIconPicker();
          break;
        case 'pin':
          widget.onPin?.call(widget.folder.id);
          break;
        case 'delete':
          _showDeleteConfirmation();
          break;
      }
    });
  }

  void _showColorPicker() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择颜色'),
        content: Wrap(
          spacing: 8,
          runSpacing: 8,
          children: [
            Colors.blue,
            Colors.green,
            Colors.orange,
            Colors.red,
            Colors.purple,
            Colors.teal,
            Colors.pink,
            Colors.indigo,
          ].map((color) => GestureDetector(
            onTap: () {
              widget.onColorChange?.call(widget.folder.id, color);
              Navigator.of(context).pop();
            },
            child: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: color,
                shape: BoxShape.circle,
                border: Border.all(
                  color: widget.folder.color == color 
                      ? Colors.white 
                      : Colors.transparent,
                  width: 2,
                ),
              ),
            ),
          )).toList(),
        ),
        actions: [
          TextButton(
            onPressed: () {
              widget.onColorChange?.call(widget.folder.id, null);
              Navigator.of(context).pop();
            },
            child: const Text('清除颜色'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  void _showIconPicker() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('选择图标'),
        content: SizedBox(
          width: 300,
          height: 200,
          child: GridView.count(
            crossAxisCount: 6,
            children: [
              Icons.folder,
              Icons.work,
              Icons.school,
              Icons.home,
              Icons.favorite,
              Icons.star,
              Icons.bookmark,
              Icons.label,
              Icons.category,
              Icons.inventory,
              Icons.archive,
              Icons.storage,
            ].map((icon) => GestureDetector(
              onTap: () {
                widget.onIconChange?.call(widget.folder.id, icon);
                Navigator.of(context).pop();
              },
              child: Container(
                margin: const EdgeInsets.all(4),
                decoration: BoxDecoration(
                  color: widget.folder.icon == icon 
                      ? Theme.of(context).colorScheme.primaryContainer
                      : Colors.transparent,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Icon(icon, size: 24),
              ),
            )).toList(),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              widget.onIconChange?.call(widget.folder.id, null);
              Navigator.of(context).pop();
            },
            child: const Text('清除图标'),
          ),
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  void _showDeleteConfirmation() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除文件夹 "${widget.folder.name}" 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          FilledButton(
            onPressed: () {
              widget.onDelete?.call(widget.folder.id);
              Navigator.of(context).pop();
            },
            style: FilledButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;
    final isDesktop = ResponsiveBreakpoints.isDesktop(context);
    
    // 计算缩进
    final indentWidth = widget.level * (isDesktop ? 24.0 : 16.0);
    
    Widget folderContent = Row(
      children: [
        // 缩进空间
        SizedBox(width: indentWidth),
        
        // 展开/折叠按钮
        if (widget.folder.hasChildren)
          GestureDetector(
            onTap: widget.onExpansionToggle,
            child: Container(
              padding: const EdgeInsets.all(4),
              child: Icon(
                widget.folder.isExpanded 
                    ? Icons.expand_more 
                    : Icons.chevron_right,
                size: 16,
                color: colorScheme.onSurfaceVariant,
              ),
            ),
          )
        else
          const SizedBox(width: 24),
        
        // 文件夹图标
        Container(
          padding: const EdgeInsets.all(4),
          decoration: widget.folder.color != null
              ? BoxDecoration(
                  color: widget.folder.color!.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(4),
                )
              : null,
          child: Icon(
            widget.folder.icon ?? Icons.folder,
            size: 20,
            color: widget.folder.color ?? colorScheme.primary,
          ),
        ),
        
        const SizedBox(width: 8),
        
        // 文件夹名称或重命名输入框
        Expanded(
          child: _isRenaming
              ? TextField(
                  controller: _renameController,
                  autofocus: true,
                  style: theme.textTheme.bodyMedium,
                  decoration: const InputDecoration(
                    isDense: true,
                    contentPadding: EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 4,
                    ),
                  ),
                  onSubmitted: (_) => _finishRename(),
                  onTapOutside: (_) => _cancelRename(),
                )
              : Text(
                  widget.folder.name,
                  style: theme.textTheme.bodyMedium?.copyWith(
                    fontWeight: widget.isSelected ? FontWeight.w600 : null,
                    color: widget.isSelected ? colorScheme.primary : null,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
        ),
        
        // 置顶图标
        if (widget.folder.isPinned)
          Padding(
            padding: const EdgeInsets.only(left: 4),
            child: Icon(
              Icons.push_pin,
              size: 14,
              color: colorScheme.primary,
            ),
          ),
        
        // 自定义尾部组件
        if (widget.trailing != null) ...[
          const SizedBox(width: 8),
          widget.trailing!,
        ],
        
        // 操作按钮（悬停时显示）
        if (widget.showActions && _isHovered && !_isRenaming)
          Row(
            mainAxisSize: MainAxisSize.min,
            children: [
              IconButton(
                icon: const Icon(Icons.more_vert, size: 16),
                onPressed: () {
                  final RenderBox renderBox = context.findRenderObject() as RenderBox;
                  final position = renderBox.localToGlobal(Offset.zero);
                  _showContextMenu(context, position);
                },
                constraints: const BoxConstraints(
                  minWidth: 32,
                  minHeight: 32,
                ),
                padding: const EdgeInsets.all(4),
              ),
            ],
          ),
      ],
    );

    // 拖拽目标装饰
    if (widget.isDragTarget) {
      folderContent = Container(
        decoration: BoxDecoration(
          border: Border.all(
            color: colorScheme.primary,
            width: 2,
          ),
          borderRadius: BorderRadius.circular(8),
        ),
        child: folderContent,
      );
    }

    Widget folderItem = AnimatedBuilder(
      animation: _scaleAnimation,
      builder: (context, child) {
        return Transform.scale(
          scale: _isDragging ? 0.95 : _scaleAnimation.value,
          child: ModernCard(
            onTap: _isRenaming ? null : widget.onTap,
            onLongPress: _isRenaming ? null : widget.onLongPress,
            isSelected: widget.isSelected,
            isHoverable: !_isRenaming,
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 6),
            child: MouseRegion(
              onEnter: (_) => setState(() => _isHovered = true),
              onExit: (_) => setState(() => _isHovered = false),
              child: folderContent,
            ),
          ),
        );
      },
    );

    // 如果启用拖拽，包装Draggable组件
    if (widget.enableDrag && !_isRenaming) {
      folderItem = Draggable<FolderDragData>(
        data: FolderDragData(
          folderId: widget.folder.id,
          folderName: widget.folder.name,
          originalIndex: 0, // 这个值应该由父组件提供
          originalParentId: widget.folder.parentId,
        ),
        feedback: Material(
          elevation: 8,
          borderRadius: BorderRadius.circular(8),
          child: Container(
            width: 200,
            padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            decoration: BoxDecoration(
              color: colorScheme.surface,
              borderRadius: BorderRadius.circular(8),
              border: Border.all(color: colorScheme.outline),
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                Icon(
                  widget.folder.icon ?? Icons.folder,
                  size: 16,
                  color: widget.folder.color ?? colorScheme.primary,
                ),
                const SizedBox(width: 8),
                Flexible(
                  child: Text(
                    widget.folder.name,
                    style: theme.textTheme.bodyMedium,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
          ),
        ),
        childWhenDragging: Opacity(
          opacity: 0.5,
          child: folderItem,
        ),
        onDragStarted: () {
          setState(() => _isDragging = true);
          _animationController.forward();
          widget.onDragStarted?.call(FolderDragData(
            folderId: widget.folder.id,
            folderName: widget.folder.name,
            originalIndex: 0,
            originalParentId: widget.folder.parentId,
          ));
        },
        onDragEnd: (details) {
          setState(() => _isDragging = false);
          _animationController.reverse();
        },
        child: folderItem,
      );
    }

    return folderItem;
  }
}

/**
 * 文件夹拖拽目标组件
 * 用于接收拖拽的文件夹
 */
class FolderDropTarget extends StatefulWidget {
  final Widget child;
  final String? targetFolderId;
  final int? targetIndex;
  final Function(FolderDragData dragData, String? targetFolderId, int? targetIndex)? onAccept;
  final bool Function(FolderDragData dragData)? onWillAccept;

  const FolderDropTarget({
    Key? key,
    required this.child,
    this.targetFolderId,
    this.targetIndex,
    this.onAccept,
    this.onWillAccept,
  }) : super(key: key);

  @override
  State<FolderDropTarget> createState() => _FolderDropTargetState();
}

class _FolderDropTargetState extends State<FolderDropTarget> {
  bool _isHovering = false;

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final colorScheme = theme.colorScheme;

    return DragTarget<FolderDragData>(
      onWillAccept: (data) {
        if (data == null) return false;
        return widget.onWillAccept?.call(data) ?? true;
      },
      onAccept: (data) {
        widget.onAccept?.call(data, widget.targetFolderId, widget.targetIndex);
      },
      onMove: (details) {
        if (!_isHovering) {
          setState(() => _isHovering = true);
        }
      },
      onLeave: (data) {
        setState(() => _isHovering = false);
      },
      builder: (context, candidateData, rejectedData) {
        return AnimatedContainer(
          duration: const Duration(milliseconds: 200),
          decoration: _isHovering
              ? BoxDecoration(
                  border: Border.all(
                    color: colorScheme.primary.withOpacity(0.5),
                    width: 2,
                  ),
                  borderRadius: BorderRadius.circular(8),
                  color: colorScheme.primaryContainer.withOpacity(0.1),
                )
              : null,
          child: widget.child,
        );
      },
    );
  }
}